package com.senlingspace.web.controller.pos;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.senlingspace.common.annotation.RepeatSubmit;
import com.senlingspace.common.core.controller.BaseController;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.core.domain.entity.SysRole;
import com.senlingspace.common.core.domain.entity.SysUser;
import com.senlingspace.common.core.page.TableDataInfo;
import com.senlingspace.common.core.redis.RedisLock;
import com.senlingspace.common.utils.StringUtils;
import com.senlingspace.framework.web.service.SysLoginService;
import com.senlingspace.system.domain.vo.*;
import com.senlingspace.system.service.ISlkjOrderService;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * pos 订单
 *
 * @author lebronjames
 * @date 2024/07/30
 */
@AllArgsConstructor
@RestController
@RequestMapping("/pos/api")
public class SlkjPosOrderController extends BaseController {

    private final ISlkjOrderService iSlkjOrderService;
    private final RedisLock redisLock;
    private final SysLoginService loginService;


    /**
     * 查询门店拥有退款权限的账号
     */
    @GetMapping("/listPre")
    public TableDataInfo listPre(Long shopId) {
        List<SysUser> list = iSlkjOrderService.listPre(shopId);

        ArrayList<PreUserVo> preUserVos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            SysUser sysUser = list.get(i);
            String userName = sysUser.getUserName();
            String nickName = sysUser.getNickName();
            List<SysRole> roles = sysUser.getRoles();
            String roleNames = roles.stream().map(SysRole::getRoleName).filter(roleName -> StringUtil.isNotBlank(roleName)).collect(Collectors.joining(","));

            PreUserVo preUserVo = new PreUserVo();
            preUserVo.setText(nickName + "(" + roleNames + ")");
            preUserVo.setValue(userName);
            preUserVos.add(preUserVo);
        }

        return getDataTable(preUserVos);
    }

    /**
     * 验证退款人信息
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/check")
    public AjaxResult refund(@RequestBody CheckVo checkVo) {
        /*验证退款人的账号*/
        if (StringUtils.isBlank(checkVo.getUserName())) {
            return error("用户名不可为空");
        }
        Boolean pass = loginService.checkPassWord(checkVo.getUserName(), checkVo.getPassword());

        if (pass) {
            List<SysUser> list = iSlkjOrderService.listPre(checkVo.getShopId());
            boolean pre = list.stream().anyMatch(user -> user.getUserName().equals(checkVo.getUserName()));
            if (pre) {

                return new AjaxResult(200, "验证成功");
            } else {
                return new AjaxResult(403, "没有权限");
            }
        } else {
            return new AjaxResult(403, "密码错误");
        }
    }

    /**
     * 订单 v2版本
     *
     * @param queryParam
     * @return {@link TableDataInfo }
     */
    @GetMapping(path = "/ordersV2")
    public TableDataInfo ordersV2(PosOrderQueryVo queryParam) {
        logger.info("POS收银台，v2版本，订单查询参数:{}", JSON.toJSONString(queryParam));
        PageInfo<PosOrderVoV2> orders = iSlkjOrderService.posOrdersV2(queryParam, true);
        logger.info("POS收银台，v2版本，订单查询结果:{}", JSON.toJSONString(orders));
        return getDataTable(orders);
    }

    /**
     * 获取小票信息
     *
     * @param orderId
     * @return {@link AjaxResult }
     */
    @GetMapping(path = "/getReceiptInfo")
    public AjaxResult getReceiptInfo(@RequestParam Long orderId) {
        logger.info("获取订单 [order_id={}] 小票信息！", orderId);
        ReceiptInfoVo receiptInfo = iSlkjOrderService.getReceiptInfo(orderId);
        logger.info("小票结果集：{}", JSON.toJSONString(receiptInfo));
        return super.success(receiptInfo);
    }

    /**
     * 核销二维码
     *
     * @param request 格式为：shop_id#verify_code#order_id
     * @return {@link AjaxResult }
     */
    @PostMapping(path = "/validateQrcode")
    public AjaxResult validateQrcode(@RequestBody JSONObject request) {
        logger.info("核销二维码：{}", request);
        String qrcode = request.getString("qrcode");
        String lockKey = "VALIDATE_QRCODE_LOCK:" + qrcode;
        RLock lock = redisLock.getRLock(lockKey);
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(15, TimeUnit.SECONDS);
            if (isLocked) {
                return iSlkjOrderService.validateQrcode(qrcode);
            }
            return AjaxResult.error("请勿重复核销！");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return AjaxResult.error("核销失败，请刷新重试！");
        } finally {
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 核销记录
     *
     * @param verificationRecordsRequest
     * @return {@link TableDataInfo }
     */
    @GetMapping(path = "/verificationRecords")
    public TableDataInfo verificationRecords(VerificationRecordsRequest verificationRecordsRequest) {
        logger.info("核销记录查询参数:{}", JSON.toJSONString(verificationRecordsRequest));
        PageInfo<VerificationRecordsVo> verificationRecords = iSlkjOrderService.verificationRecords(verificationRecordsRequest);
        logger.info("核销记录查询结果:{}", JSON.toJSONString(verificationRecords));
        return getDataTable(verificationRecords);
    }

}
